package algorithm.easy;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class Solution145 {

    //输入：root = [1,null,2,3]
    //输出：[3,2,1]
    public static List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        TreeNode node = root;
        TreeNode prev = null;
        if(root==null){
            return  null;
        }
        while (node!=null || !stack.isEmpty()){
            if(node!=null){
                stack.push(node);
                node = node.left;
            }else{
                node = stack.pop();
                if(node.right!=null && node.right!=prev){
                    stack.push(node);
                    node = node.right;

                }else{
                    list.add(node.val);
                    prev = node;
                    node = null;
                }
            }
        }
        return list;
    }

    public static void main(String[] args){
        TreeNode treeNode = TreeNode.init110();
        System.out.println(postorderTraversal(treeNode));
    }

}
